DIR_DJANGO_LOCALES ?= locale
DJANGO_MAKEMESSAGES_ARGS ?= --ignore "$(DIR_BUILD)/*" --no-location
DJANGO_COMPILEMESSAGES_ARGS ?= --ignore "$(DIR_BUILD)/*"

# try to detect a PO editor for translations
PO_EDITOR ?= $(shell which virtaal poedit | head -1)


.PHONY: help-python-django
help-python-django:
	@echo "Targets related to Django (Python):"
	@echo "    django-migrate"
	@echo "    django-translate"
	@echo

help-python: help-python-django

virtualenv-check:
	@# this should fail if dependencies are missing or no virtualenv is active
	@if $(RUN_PYTHON) manage.py check >/dev/null; then true; else \
		echo >&2 'Some python-related dependencies are missing'; \
		echo >&2 '  You have two options:'; \
		echo >&2 '    1. Install dependencies system-wide. See the $(VIRTUALENV_REQUIREMENTS_FILE) file.'; \
		echo >&2 '    2. Run "make virtualenv-update && . $(ACTIVATE_VIRTUALENV)".'; \
		false; fi

.PHONY: django-migrate
django-migrate:
	$(RUN_PYTHON) manage.py makemigrations
	$(RUN_PYTHON) manage.py migrate

.PHONY: django-translate
django-translate:
	@mkdir -p "$(DIR_DJANGO_LOCALES)"
	$(RUN_PYTHON) manage.py makemessages $(DJANGO_MAKEMESSAGES_ARGS) $(shell if [ -n "$(DJANGO_WANTED_LOCALES)" ]; then printf -- '--locale %s\n' $(DJANGO_WANTED_LOCALES); else printf -- '--all'; fi)
	@if [ -z "$$(find "$(DIR_DJANGO_LOCALES)" -type f -name "*.po")" ]; then \
		echo >&2 "There are no PO files below '$(DIR_DJANGO_LOCALES)': maybe you want to run the following?"; \
		echo >&2 "    make django-translate DJANGO_WANTED_LOCALES='FOO BAR'"; false; fi
	if [ -n "$(PO_EDITOR)" ]; then find "$(DIR_DJANGO_LOCALES)" -type f -name "*.po" | xargs -r -n 1 "$(PO_EDITOR)"; fi
	$(RUN_PYTHON) manage.py compilemessages $(DJANGO_COMPILEMESSAGES_ARGS)
